package org.hit.burkun.index.term;

import java.util.Collection;
import java.util.LinkedList;

import org.hit.burkun.db.DBHelper;
import org.hit.burkun.db.DBTypeConverter;
import org.hit.burkun.db.DBTypeConverter.DATATYPE;
import org.hit.burkun.index.term.IndexSynonym.SynAndType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IndexSynonymDump {

	private DBHelper dbh;
	private String[] insertFileds = { "offical_name", "synonm", "synonm_type",
			"source_termid1", "source_termid2" };
	private DBTypeConverter dataTypesCovert;
	private String tbName;
	/*
	 * CREATE TABLE `all_synonms` ( `primary_id` int(11) NOT NULL
	 * AUTO_INCREMENT, `offical_name` varchar(800) NOT NULL, `synonm`
	 * varchar(800) DEFAULT NULL, `synonm_type` varchar(45) DEFAULT 'EXACT',
	 * `source_termid1` int(11) DEFAULT NULL, `source_termid2` int(11) DEFAULT
	 * NULL, PRIMARY KEY (`primary_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
	 */
	private static Logger logger = LoggerFactory
			.getLogger(IndexSynonymDump.class);

	public IndexSynonymDump(DBHelper dbh, String tbName) {
		this.dbh = dbh.clone();
		this.tbName = tbName;

		DATATYPE[] dataTypes = new DATATYPE[insertFileds.length];
		dataTypes[3] = DATATYPE.I;
		dataTypes[4] = DATATYPE.I;
		dataTypesCovert = new DBTypeConverter(dataTypes);
	}

	public void saveToTable(Collection<IndexSynonym> data) {
		logger.debug("save term data in to " + tbName + "...");
		LinkedList<String[]> insertData = new LinkedList<>();
		// 加一个判断
		for (IndexSynonym term : data) {
			if (term.synonyms.size() != 0) {
				// 没有同义词的就不处理啦
				for (SynAndType syn : term.synonyms) {
					String[] line = new String[insertFileds.length];
					line[0] = term.officalName;
					line[1] = syn.synonym;
					line[2] = syn.synType;
					line[3] = term.sourceID;
					line[4] = syn.synSource;
					insertData.add(line);
				}
			}
		}
		dbh.connectionDB();
		dbh.insertBatch(tbName, insertFileds, insertData, dataTypesCovert);
		dbh.disconnection();
		logger.debug("save term data in to " + tbName + " done!");
	}

}
